package com.hdcircles.autoform.ui.label.fragment;

import android.app.ActivityOptions;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.hdcircles.autoform.R;
import com.hdcircles.autoform.base.BaseFragment;
import com.hdcircles.autoform.model.bean.FormBean;
import com.hdcircles.autoform.presenter.ShareLabelPresenter;
import com.hdcircles.autoform.presenter.contract.ShareLabelContract;
import com.hdcircles.autoform.ui.label.Service.FormService;
import com.hdcircles.autoform.ui.label.activity.FillFormActivity;
import com.hdcircles.autoform.ui.label.activity.FormListActivity;
import com.hdcircles.autoform.ui.label.adapter.SharedFormAdapter;
import com.hdcircles.autoform.ui.main.activity.MainActivity;
import com.hdcircles.autoform.ui.main.fragment.UserFragment;
import com.hdcircles.autoform.util.SharedPreferenceUtil;
import com.hdcircles.autoform.util.SnackbarUtil;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by hdcircles on 2016/9/27.
 */

public class ShareLabelFragment extends BaseFragment<ShareLabelPresenter> implements ShareLabelContract.View
        ,SharedFormAdapter.onFillClickListener,SharedFormAdapter.onViewClickListener{

    @BindView(R.id.rv_from)
    RecyclerView rvFrom;
    @BindView(R.id.refreshLayout)
    SwipeRefreshLayout refreshLayout;

    private SharedFormAdapter adapter;

    private FormService.FormBinder formBinder;

    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            formBinder= (FormService.FormBinder) iBinder;
            formBinder.startFormService(SharedPreferenceUtil.getUserEmail());
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            formBinder.setStop(true);
        }
    };

    private BroadcastReceiver formServiceReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            List<FormBean> formBeanList=intent.getParcelableArrayListExtra("formList");
            refreshData(formBeanList);
        }
    };


    private BroadcastReceiver userQuitReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (null!=formBinder) formBinder.setStop(true);
        }
    };


    private void refreshData(List<FormBean> formBeanList) {
        adapter.setFormBeanList(formBeanList);
        adapter.notifyDataSetChanged();
        refreshLayout.setRefreshing(false);
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_share_label;
    }

    @Override
    protected void initEventAndData() {
        adapter=new SharedFormAdapter();
        rvFrom.setLayoutManager(new LinearLayoutManager(getContext()));
        rvFrom.setAdapter(adapter);
        bindService();
        IntentFilter intentFilter=new IntentFilter(FormService.BROADCAST_SERVICE_ACTION);
        getContext().registerReceiver(formServiceReceiver,intentFilter);
        IntentFilter filter=new IntentFilter(UserFragment.USER_QUIT_ACTION);
        getContext().registerReceiver(userQuitReceiver,filter);
        adapter.setOnItemClickListener(new SharedFormAdapter.onItemClickListener() {
            @Override
            public void onItemClick(FormBean formBean, View view) {
//                Intent intent=new Intent(getContext(),FillFormActivity.class);
//                Bundle bundle=new Bundle();
//                bundle.putParcelable("form",formBean);
//                intent.putExtras(bundle);
//                intent.putExtra("isEmpty",false);
//                intent.putExtra("isShared",true);
//                ActivityOptions options=ActivityOptions.makeSceneTransitionAnimation(getActivity(),view,"shareView");
//                startActivity(intent,options.toBundle());
            }
        });
//        refreshLayout.post(new Runnable() {
//            @Override
//            public void run() {
//                refreshLayout.setRefreshing(true);
//            }
//        });
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPresenter.getFormData();
            }
        });
        adapter.setUserNameListener(new SharedFormAdapter.getUserNameListener() {
            @Override
            public void getUser(String creator, TextView textView) {
                mPresenter.getUser(creator,"",textView);
            }
        });
        adapter.setOnFillClickListener(this);
        adapter.setOnViewClickListener(this);
    }

    public void bindService(){
        Intent intent=new Intent(getContext(),FormService.class);
        getContext().bindService(intent,connection, Context.BIND_AUTO_CREATE);
    }

    public void unbindService(){

        getContext().unbindService(connection);
    }

    @Override
    public void showContent(List<FormBean> formBeanList) {
        refreshData(formBeanList);
    }

    @Override
    public void setUserName(String time, String name, TextView textView) {
        textView.setText("来自于:\t"+name);
    }

    @Override
    public void showError(String msg) {
//        SnackbarUtil.showShort(refreshLayout,msg);
        refreshLayout.setRefreshing(false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getContext().unregisterReceiver(formServiceReceiver);
        getContext().unregisterReceiver(userQuitReceiver);
        unbindService();
    }

    @Override
    public void onFill(FormBean form, View view) {
        Intent intent=new Intent(getActivity(), FillFormActivity.class);
        Bundle bundle=new Bundle();
        bundle.putParcelable("form",form);
        intent.putExtras(bundle);
        intent.putExtra("isEmpty",true);
        ActivityOptions options=ActivityOptions.makeSceneTransitionAnimation(mActivity,view,"shareView");
        getActivity().startActivity(intent,options.toBundle());
    }

    @Override
    public void onView(String formId, String writerEmail, View view) {
        Intent intent=new Intent(getActivity(), FormListActivity.class);
        intent.putExtra("formId",formId);
        intent.putExtra("writerEmail",writerEmail);
        ActivityOptions options=ActivityOptions.makeSceneTransitionAnimation(mActivity,view,"shareView");
        getActivity().startActivity(intent,options.toBundle());
    }
}
